﻿// CameraParameters
// Container for camera parameters
// 
// FLMScan - Featured by FabLab Munich

using System;
using System.IO;
using System.Xml;
using System.Globalization;
using log4net;

namespace FLMScan.Parameters
{
    class CameraParameters
    {
        private ILog logger;
        private int cameraId;
        
        private const int DefaultCameraId = 1;

        private const String CameraIdParameter = "CameraId";           
        
        public CameraParameters()
        {
            logger = LogManager.GetLogger(typeof(CameraParameters));

            SetDefaultValues();
        }

        public CameraParameters(string configurationFilePath)
        {
            logger = LogManager.GetLogger(typeof(CameraParameters));

            SetDefaultValues();
            Initialize(configurationFilePath);            
        }

        public int CameraId
        {
            get { return cameraId; }
            set { cameraId = value; }
        }        

        private void Initialize(string configFilePath)
        {
            try
            {
                TextReader reader = new StreamReader(configFilePath);
                GetConfigValues(reader);                
            }
            catch (FileNotFoundException)
            {

            }
        }

        public void Serialize(XmlTextWriter textWriter)
        {
            FLMScanParameters.SerializeParameter(textWriter, CameraIdParameter, CameraId.ToString());
        }

        private void SetDefaultValues()
        {
            cameraId = DefaultCameraId;
        }

        private void GetConfigValues(TextReader reader)
        {
            XmlTextReader xmlReader = new XmlTextReader(reader);
            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == XmlNodeType.Element &&
                    xmlReader.Name.Equals("add") &&
                    xmlReader.MoveToNextAttribute())
                {
                    try
                    {
                        switch (xmlReader.Name)
                        {
                            case CameraIdParameter:
                                CameraId = int.Parse(xmlReader.Value);
                                logger.DebugFormat(FLMScanParameters.LogSettingParameterToValue, CameraIdParameter, CameraId);
                                break;                            
                        }
                    }
                    catch (System.Exception e)
                    {
                        System.Diagnostics.Debug.Assert(false, e.ToString());
                        logger.Error(FLMScanParameters.LogExceptionReadingParametersFromConfigFile, e);
                    }
                }
            }

            xmlReader.Close();
        }
    }
}
